package com.adopapa.nezhacloud.register.service;

import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.adopapa.nezhacloud.common.JsonUtil;
import com.adopapa.nezhacloud.common.Tools;
import com.adopapa.nezhacloud.ddd.service.BaseService;
import com.adopapa.nezhacloud.redis.RedisService;
import com.adopapa.nezhacloud.register.conf.AppProperties;
import com.adopapa.nezhacloud.register.conf.RegisterConstants;
import com.adopapa.nezhacloud.register.domain.StudentInfo;
import com.adopapa.nezhacloud.register.domain.StudyStat;
import com.fasterxml.jackson.databind.JsonNode;

import jakarta.annotation.PostConstruct;

@Service
public class DataSystemService extends BaseService {

	@Autowired
	private RedisService redisService;
	@Autowired
	private StudentInfoService studentInfoService;
	@Autowired
	private StudyStatService studyStatService;

	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private AppProperties appProperties;

	@PostConstruct
	public void loadData2Cache() {
		StudentInfo example = new StudentInfo();
		int pageNo = 1;
		int pageSize = 100;
		RedisTemplate<String, Object> redisTemplate = //
				redisService.getRedisTemplate(RegisterConstants.REGISTER_REDIS_DBINDEX);
		Page<StudentInfo> page = studentInfoService.getStudentInfoPage(pageNo, pageSize, example);
		logger.info("load data page {}, size {}, pages {}, total {}", pageNo, pageSize, //
				page.getTotalPages(), page.getTotalElements());

		while (page.getContent().size() > 0) {
			for (StudentInfo studentInfo : page) {
				redisTemplate.opsForHash().put("student", studentInfo.getCellphone(), studentInfo.getName());
			}
			pageNo++;

			page = studentInfoService.getStudentInfoPage(pageNo, pageSize, example);

			logger.info("load data page {}, size {}, pages {}, total {}", pageNo, pageSize, //
					page.getTotalPages(), page.getTotalElements());
		}
	}

	public void batchSaveStudyStat(List<StudyStat> studyStats) {
		List<StudyStat> stats = new LinkedList<StudyStat>();
		for (StudyStat studyStat : studyStats) {
			studyStat.setCreateTime(Instant.now());
			if (!Tools.empty(studyStat.getStartDate())) {
				studyStat.setStartTime(studyStat.getStartDate().toInstant());
			}
			if (!Tools.empty(studyStat.getEndDate())) {
				studyStat.setEndTime(studyStat.getEndDate().toInstant());
			}

			RedisTemplate<String, Object> redisTemplate = //
					redisService.getRedisTemplate(RegisterConstants.REGISTER_REDIS_DBINDEX);

			String name = (String) redisTemplate.opsForHash().get("student", studyStat.getCellphone());

//			if (!Tools.empty(name)) {
//				studyStat.setName(name);
//				stats.add(studyStat);
//			}
//			studyStat.setName(name);
			stats.add(studyStat);

		}
		studyStatService.saveStudyStats(stats);

//		TimerManager.schedule(() -> {
//			asyncUpstudent();
//			return null;
//		}, 30000L);

	}

	public void asyncUpstudent() {
		StudyStat example = new StudyStat();
		example.setRegisted(Boolean.FALSE);
		
		int pageNo = 1;
		int pageSize = 100;
		Page<StudyStat> page = studyStatService.getStudyStatPage(pageNo, pageSize, example);
		logger.info("load data page {}, size {}, pages {}, total {}", pageNo, pageSize, //
				page.getTotalPages(), page.getTotalElements());

		while (page.getContent().size() > 0) {
			// 远程注册
			for (StudyStat studyStat : page) {
				remoteRegist(studyStat);
			}

			pageNo++;
			page = studyStatService.getStudyStatPage(pageNo, pageSize, example);
			logger.info("load data page {}, size {}, pages {}, total {}", pageNo, pageSize, //
					page.getTotalPages(), page.getTotalElements());
		}
	}

	private void remoteRegist(StudyStat studyStat) {
		try {
			logger.info("remote registing {} {}", studyStat.getName(), studyStat.getCellphone());
//			try {
//				name = URLEncoder.encode(name, "UTF-8");
//			} catch (Exception e) {
//				logger.error(ExceptionUtils.getStackTrace(e));
//			}
			String remoteUrl = String.format(appProperties.getRemoteStudentUrl(), studyStat.getName(),
					studyStat.getCellphone());

			HttpHeaders headers = getHeaders(Collections.emptyMap());

			ResponseEntity<String> response = restTemplate.getForEntity(remoteUrl, String.class, headers);
			logger.info(response.getBody());
			// {"errorCode":"0000","errorMsg":"保存成功","data":"4120069596278833251"}
			JsonNode jsonNode = JsonUtil.objectMapper.readTree(response.getBody());
			if ("0000".equals(jsonNode.get("errorCode").asText())) {
				logger.info("更新注册信息");
				studyStat.setStudentId(jsonNode.get("data").asText());
				studyStat.setRegisted(Boolean.TRUE);

				studyStatService.saveStudyStat(studyStat);
			}

		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}

	}

	private static HttpHeaders getHeaders(Map<String, String> params) {
		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
		// headers.add("authorization", authorization);
		if (!Tools.empty(params)) {
			params.forEach((K, V) -> {
				headers.add(K, V);
			});
		}

		return headers;

	}

	public void asyncBatchEnroll() {
		StudyStat example = new StudyStat();
		example.setRegisted(Boolean.TRUE);

		int pageNo = 1;
		int pageSize = 100;
		Page<StudyStat> page = studyStatService.getStudyStatPage(pageNo, pageSize, example);
		logger.info("load data page {}, size {}, pages {}, total {}", pageNo, pageSize, //
				page.getTotalPages(), page.getTotalElements());

		while (page.getContent().size() > 0) {
			// 远程登记班级
			String studentIds = page.getContent().stream().map(e -> e.getStudentId())//
					.collect(Collectors.joining(","));

			remoteEnroll(studentIds);

			pageNo++;
			page = studyStatService.getStudyStatPage(pageNo, pageSize, example);
			logger.info("load data page {}, size {}, pages {}, total {}", pageNo, pageSize, //
					page.getTotalPages(), page.getTotalElements());

		}

	}

	private void remoteEnroll(String studentIds) {
		logger.info("remote enroll {}", studentIds);
		String remoteUrl = String.format(appProperties.getRemoteEnrollUrl(), studentIds);
		HttpHeaders headers = getHeaders(Collections.emptyMap());
		ResponseEntity<String> response = restTemplate.getForEntity(remoteUrl, String.class, headers);
		logger.info(response.getBody());

	}
}
